package com.ldk.base.framework.datasource.generator;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.ldk.base.framework.datasource.DataSourceDriver;

/**
 * Mysql表实体生成器
 * @author xiangwl
 *
 */
public class MySqlEntityGenerator extends EntityGenerator {
	
	/**
	 * 构造函数
	 * @param serverName
	 * @param portNumber
	 * @param databaseName
	 * @param user
	 * @param password
	 */
	public MySqlEntityGenerator(String serverName, int portNumber, String databaseName, String user, String password){
		setServerName(serverName);
		setPortNumber(portNumber);
		setDatabaseName(databaseName);
		setUser(user);
		setPassword(password);
	}
	
	@Override
	protected List<String> getTables() {
		String sql = String.format("select table_name from information_schema.tables where table_schema='%s' and table_type='%s';", getDatabaseName(),"base table");
		
		List<String> tables = new ArrayList<String>();
		try{
			Connection conn = getConnection();
			if(conn != null){
				Statement statement =  conn.createStatement();
				ResultSet rs = statement.executeQuery(sql);
				if(rs != null){
					while (rs.next()) {
						tables.add(rs.getString("table_name"));
					}
				}
				statement.close();
				conn.close();
			}
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		return tables;
	}

	@Override
	protected List<TableColumn> getTableColums(String table) {
		String sql = String.format("select COLUMN_NAME,IS_NULLABLE,DATA_TYPE,NUMERIC_PRECISION,COLUMN_KEY, EXTRA,COLUMN_COMMENT from information_schema.columns where table_schema='%s' and table_name='%s' order by ORDINAL_POSITION", getDatabaseName(), table);
		
		List<TableColumn> columns = new ArrayList<TableColumn>();
		try{
			Connection conn = getConnection();
			if(conn != null){
				Statement statement =  conn.createStatement();
				ResultSet rs = statement.executeQuery(sql);
				if(rs != null){
					while (rs.next()) {
						TableColumn column = new TableColumn();
						String columnName = rs.getString("COLUMN_NAME");
						column.setColumnName(columnName);
						String propertyName = underlineToCamel(columnName);
						column.setPropertyName(propertyName);
						String isNUllable = rs.getString("IS_NULLABLE");
						if(!StringUtils.isEmpty(isNUllable) && isNUllable.equalsIgnoreCase("no")){
							column.setIsNullable(false);
						}
						else{
							column.setIsNullable(true);
						}
						String dataType = rs.getString("DATA_TYPE");
						column.setDataType(getColumnDataType(dataType));
						int precision = rs.getInt("NUMERIC_PRECISION");
						column.setPrecision(precision);
						String key = rs.getString("COLUMN_KEY");//PRI
						if(!StringUtils.isEmpty(key) && key.equalsIgnoreCase("pri")){
							column.setIsKey(true);
						}
						else{
							column.setIsKey(false);
						}
						String extra = rs.getString("EXTRA");//auto_increment
						if(!StringUtils.isEmpty(extra) && extra.equalsIgnoreCase("auto_increment")){
							column.setIsAutoIncrement(true);
						}
						else{
							column.setIsAutoIncrement(false);
						}
						String comment = rs.getString("COLUMN_COMMENT");
						column.setComment(comment);
						//添加
						columns.add(column);
					}
				}
				statement.close();
				conn.close();
			}
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		return columns;
	}

	@Override
	protected Connection getConnection() {
		String url = String.format("jdbc:mysql://%s:%d/%s?characterEncoding=utf8", 
									getServerName(),getPortNumber(),getDatabaseName());
		Connection conn = null;
		try{
			Class.forName(DataSourceDriver.MYSQL.getNoXADriver());
			conn = DriverManager.getConnection(url, getUser(), getPassword());
		}
		catch(Exception e){
			
		}
		return conn;
	}

	@Override
	protected DBType getDbType() {
		return DBType.MySQL;
	}

}
